package com.jtech.together.view.adapter;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jtech.together.R;
import com.jtech.together.manager.UserManager;
import com.jtech.together.model.AddFriendMessage;
import com.jtech.together.util.IM;
import com.jtech.together.util.ImageUtils;
import com.jtech.together.util.Util;
import com.jtechlib2.adapter.RecyclerSwipeAdapter;
import com.jtechlib2.view.RecyclerHolder;

import cn.bmob.newim.bean.BmobIMConversation;
import cn.bmob.newim.bean.BmobIMMessage;
import cn.bmob.newim.bean.BmobIMUserInfo;

/**
 * 消息列表适配器
 * Created by wuxubaiyang on 2017/5/14.
 */

public class MessageAdapter extends RecyclerSwipeAdapter<BmobIMConversation> {
    private static final String SWIPE_BACKGROUND_COLOR = "FF4444";
    private static final int TYPE_ADD_FRIEND_MESSAGE = 0x1451;
    private static final int MAX_SWIPE_LENGTH = 600;

    private OnMessageListener onMessageListener;

    public MessageAdapter(Context context) {
        super(context);
    }

    /**
     * 设置消息监听
     *
     * @param onMessageListener
     */
    public void setOnMessageListener(OnMessageListener onMessageListener) {
        this.onMessageListener = onMessageListener;
    }

    /**
     * 获取用户id
     *
     * @return
     */
    public String getUserId(int position) {
        return getUserInfo(position)
                .getUserId();
    }

    /**
     * 获取用户对象
     *
     * @param position
     * @return
     */
    public BmobIMUserInfo getUserInfo(int position) {
        BmobIMMessage imMessage = getLastMessage(position);
        return isMine(imMessage.getFromId()) ?
                UserManager.getIMUserInfo(imMessage.getToId()) : imMessage.getBmobIMUserInfo();
    }

    /**
     * 获取会话的最后一条消息
     *
     * @param position
     * @return
     */
    public BmobIMMessage getLastMessage(int position) {
        return getItem(position)
                .getMessages().get(0);
    }

    /**
     * 判断是否为当前用户
     *
     * @param userId
     * @return
     */
    private boolean isMine(String userId) {
        return userId.equals(UserManager.getCurrentUserId());
    }

    @Override
    public int getItemViewType(int position) {
        if (AddFriendMessage.isAddFriend(getLastMessage(position))) {
            return TYPE_ADD_FRIEND_MESSAGE;
        }
        return super.getItemViewType(position);
    }

    @Override
    public void clearView(RecyclerHolder recyclerHolder) {
        recyclerHolder.itemView
                .setBackgroundColor(getContext().getResources().getColor(android.R.color.transparent));
        recyclerHolder.getView(R.id.cardview_message).setAlpha(1f);
    }

    @Override
    public View getSwipeView(RecyclerHolder recyclerHolder) {
        return recyclerHolder.getView(R.id.cardview_message);
    }

    @Override
    public void onSwipe(RecyclerHolder recyclerHolder, int direction, float dx) {
    }

    @Override
    public void onSwipeStart(RecyclerHolder recyclerHolder, float dx) {
        dx = Math.abs(dx);
        if (MAX_SWIPE_LENGTH >= dx) {
            float ratio = dx / MAX_SWIPE_LENGTH;
            int c = (int) (ratio * 100);
            //设置背景颜色
            recyclerHolder.itemView
                    .setBackgroundColor(Color.parseColor("#" + (c < 10 ? "0" + c : c) + SWIPE_BACKGROUND_COLOR));
        }
    }

    @Override
    protected View createView(LayoutInflater layoutInflater, ViewGroup viewGroup, int viewType) {
        if (viewType == TYPE_ADD_FRIEND_MESSAGE) {
            return layoutInflater.inflate(R.layout.view_message_add_item, viewGroup, false);
        }
        return layoutInflater.inflate(R.layout.view_message_item, viewGroup, false);
    }

    @Override
    protected void convert(RecyclerHolder holder, final BmobIMConversation model, int position) {
        BmobIMMessage imMessage = getLastMessage(position);
        //如果是发送者id是当前用户，则获取目标用户的用户信息
        final BmobIMUserInfo userInfo = getUserInfo(position);
        //通用参数设置
        //设置用户头像
        ImageUtils.showCircleImage(getContext(), userInfo.getAvatar(), holder.getImageView(R.id.imageview_message_avatar),
                R.drawable.ic_default_avatar, R.drawable.ic_default_avatar);
        //设置用户昵称
        holder.setText(R.id.textview_message_nickname, userInfo.getName());
        //设置最新消息
        holder.setText(R.id.textview_message_content, IM.getMessageContent(imMessage));
        //判断是否为添加好友消息
        if (getItemViewType(position) == TYPE_ADD_FRIEND_MESSAGE) {
            //设置接受按钮点击事件
            holder.setClickListener(R.id.textview_message_add_accept, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (null != onMessageListener) {
                        onMessageListener.acceptAddFriend(model, userInfo);
                    }
                }
            });
        } else {
            //设置最新消息的发送时间
            holder.setText(R.id.textview_message_date, Util.formatMessageDate(imMessage.getCreateTime()));
            //显示或隐藏未读数
            holder.setViewVisible(R.id.textview_message_unread, model.getUnreadCount() > 0);
            //设置阅读数
            holder.setText(R.id.textview_message_unread, (model.getUnreadCount() > 99 ? 99 : model.getUnreadCount()) + "");
        }
    }

    /**
     * 消息操作监听
     */
    public interface OnMessageListener {
        void acceptAddFriend(BmobIMConversation conversation, BmobIMUserInfo userInfo);
    }
}